package zack.project.domain.trade.service.refund.business.impl;

import zack.project.domain.trade.model.aggregate.GroupBuyRefundAggregate;
import zack.project.domain.trade.model.entity.GroupBuyTeamEntity;
import zack.project.domain.trade.model.entity.NotifyTaskEntity;
import zack.project.domain.trade.model.entity.TradeRefundOrderEntity;
import zack.project.domain.trade.model.valobj.TeamRefundSuccess;
import zack.project.domain.trade.service.refund.business.AbstractRefundOrderStrategy;
import zack.project.types.enums.GroupBuyOrderEnumVO;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

/**
 * 发起退单（已成团&已支付），锁单量-1、完成量-1、组队订单状态更新、发送退单消息（MQ）
 *
 * 2025/7/8 07:45
 */
@Slf4j
@Service("paidTeam2RefundStrategy")
public class PaidTeam2RefundStrategy extends AbstractRefundOrderStrategy {

    @Override
    public void refundOrder(TradeRefundOrderEntity tradeRefundOrderEntity) {
        log.info("退单；已支付，已成团 userId:{} teamId:{} orderId:{}", tradeRefundOrderEntity.getUserId(), tradeRefundOrderEntity.getTeamId(), tradeRefundOrderEntity.getOrderId());

        GroupBuyTeamEntity groupBuyTeamEntity =
                repository.queryGroupBuyTeamByTeamId(tradeRefundOrderEntity.getTeamId());
        Integer completeCount = groupBuyTeamEntity.getCompleteCount();

        // 最后一笔也退单，则更新拼团订单为失败
        //这个PaidTeam2RefundStrategy节点是根据DataNodeFilter节点查询到的groupBuyTeamEntity和MarketProductEntity
        // 这两个实体对应数据库的两条记录，根据拼团队伍状态和拼团详单状态获得的，当队伍状态是Complete，详单状态是已支付时会走到这个节点
        //此时，队伍已经拼团成功，如果完成数是1，有两种可能:
        //1.targetCount就是1，所以这个唯一的用户退单，要把队伍状态改为FAIL
        //2.targetCount不是1，但别的队员都退单只剩一个人，此时这个人退单，队伍状态也要改成Fail
        //总之 ： 队伍完成数不是1，则队伍状态改成COMPLETE_FAIL，队伍完成数是1，队伍只剩一个人，队伍状态改为FAIL，后续就不会再退单了，
        // 在获取退单类型(RefundTypeVO)的时候没有对应的退单策略
        GroupBuyOrderEnumVO groupBuyOrderEnumVO = 1 == completeCount ?
                GroupBuyOrderEnumVO.FAIL : GroupBuyOrderEnumVO.COMPLETE_FAIL;

        // 1. 退单，已支付&已成团
        NotifyTaskEntity notifyTaskEntity =
                repository.paidTeam2Refund(GroupBuyRefundAggregate.buildPaidTeam2RefundAggregate(tradeRefundOrderEntity, -1,
                        -1,
                        groupBuyOrderEnumVO));

        // 2. 发送MQ消息 - 发送MQ，恢复锁单库存量使用
        sendRefundNotifyMessage(notifyTaskEntity, "已支付，已成团");

    }

    @Override
    public void reverseStock(TeamRefundSuccess teamRefundSuccess) throws Exception {
        log.info("退单；已支付、已成团，队伍组队结束，不需要恢复锁单量 {} {} {}", teamRefundSuccess.getUserId(), teamRefundSuccess.getActivityId(), teamRefundSuccess.getTeamId());
    }

}
